package com.example.templateapp.ui.resetPw

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.rxLifeScope
import com.example.templateapp.R
import com.example.templateapp.databinding.ActivityResetPwBinding
import com.example.templateapp.model.PasswordReset
import com.example.templateapp.ui.login.LoginActivity
import com.example.templateapp.util.LoadingDialogFactory
import com.example.templateapp.util.VerifyUtil.isEmptyThenToast
import com.example.templateapp.util.VerifyUtil.isPwValid
import com.example.templateapp.util.toastException
import com.xuexiang.xutil.tip.ToastUtils
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.param.toResponse

class ResetPwActivity : AppCompatActivity() {

    private lateinit var binding: ActivityResetPwBinding

    private var resetModel = PasswordReset()

    private val loadingDialog by lazy { LoadingDialogFactory.getDialog(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_reset_pw)

        binding.model = resetModel
        binding.title.setLeftClickListener {
            finish()
        }

        binding.resetBtn.setOnClickListener {
            if (isEmptyThenToast(resetModel.originPw.value, "原密码")
                || isEmptyThenToast(resetModel.nowPw.value, "新密码")
                || isEmptyThenToast(resetModel.repeatNowPw.value, "新密码确认")
                || isPwValid(
                    resetModel.originPw.value!!,
                    resetModel.nowPw.value!!,
                    resetModel.repeatNowPw.value!!
                ).not()
            ) {
                return@setOnClickListener
            }

            doReset()

        }
    }

    private fun doReset() = rxLifeScope.launch({
        val result = RxHttp.postJson("Url.resetPw")
            .add("id", "getUserInfo()!!.id")
            .add("newPassword", resetModel.nowPw.value)
            .add("originalPassword", resetModel.originPw.value)
            .toResponse<String>()
            .await()

        if (result.succeed()) {
            ToastUtils.toast("密码修改成功,请重新登录")
            val intent = Intent(this@ResetPwActivity, LoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            startActivity(intent)
            finish()
        }

    }, {
        toastException(it)
        loadingDialog.dismiss()
    },
        { loadingDialog.show() },
        { loadingDialog.dismiss() }
    )

    override fun onDestroy() {
        super.onDestroy()
        loadingDialog.recycle()
    }
}